package com.example.myapplication.Services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.myapplication.R;

public class MusicService extends Service {
  private MediaPlayer mediaPlayer;

  @Override public void onCreate() {
    super.onCreate();
    mediaPlayer = MediaPlayer.create(this, R.raw.test_music);
    mediaPlayer.setLooping(true);

  }

  @Override public int onStartCommand(Intent intent, int flags, int startId) {
    if (!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
    }
    Toast.makeText(this, "正在播放音乐", Toast.LENGTH_SHORT);
    return START_STICKY;
  }

  @Override public void onDestroy() {
    super.onDestroy();
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    mediaPlayer.release();

  }

  @Nullable @Override public IBinder onBind(Intent intent) {
    return null;
  }
}
